package com.uvstu.common.utils;

import cn.uvtool.exception.TClientException;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class ReadMbUtil {

    public static String readHtml(String fileName) throws TClientException {
        String uploadPath = "template/".concat(fileName);
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(uploadPath);
        String str = readHtmlToString(is);
        return str;
    }

    /**
     * 读取html文件为String
     * @return
     * @throws Exception
     */
    private static String readHtmlToString(InputStream is) throws TClientException {
        Reader reader = null;
        try {
            if (is ==  null) {
                throw new TClientException("指定路径下未找到模板文件");
            }
            reader = new InputStreamReader(is, "UTF-8");
            StringBuilder sb = new StringBuilder();
            int bufferSize = 1024;
            char[] buffer = new char[bufferSize];
            int length = 0;
            while ((length = reader.read(buffer, 0, bufferSize)) != -1){
                sb.append(buffer, 0, length);
            }
            return sb.toString();
        }catch (Exception e){
            throw new TClientException("获取模板文件失败！错误信息："+e.getMessage());
        }finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                throw new TClientException("错误信息："+e.getMessage());
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch ( IOException e) {
                throw new TClientException("错误信息："+e.getMessage());
            }
        }
    }

}
